package com.dongqb.win;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Image;
import java.awt.Point;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

import com.dongqb.bean.StockInfo;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONUtil;

import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTabbedPane;
import javax.swing.JTextPane;

public class StockDialog {

	private JFrame frame;
	private int mouseX, mouseY;
	private JImagePanel panel_min;
	private JImagePanel panel_day;
	private JImagePanel panel_week;
	private JImagePanel panel_month;
	public JImagePanel panelRun;
	private String code;
	private JLabel name;
	private JLabel prvice;
	private JTabbedPane tabbedPane;
	private JLabel sell_5;
	private JLabel sell_2;
	private JLabel sell_3;
	private JLabel sell_1;
	private JLabel buy_1;
	private JLabel buy_2;
	private JLabel buy_3;
	private JLabel buy_4;
	private JLabel buy_5;
	private JLabel sell_4;
	private JLabel npan;
	private JLabel wpan;
	private JTextPane infoPane;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					StockDialog window = new StockDialog();
					window.frame.setVisible(true);
					window.loadData(null);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public StockDialog() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setForeground(Color.DARK_GRAY);
		frame.setBackground(Color.DARK_GRAY);
		frame.setIconImage(Toolkit.getDefaultToolkit().getImage(MainWin.class.getResource("/com/dongqb/exe/info.png")));
		frame.setBounds(100, 100, 709, 500);
		frame.setResizable(false);
		frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		frame.setUndecorated(true); // 取消原生标题栏
		frame.setType(Window.Type.UTILITY); // 关键设置，不显示在任务栏
		frame.setAlwaysOnTop(true);// 总置顶显示

		// 主面板使用BorderLayout
		JPanel mainPanel = new JPanel(new BorderLayout());
		frame.setContentPane(mainPanel);

		// 创建自定义标题栏
		JPanel titleBar = new JPanel(new BorderLayout());
		titleBar.setBackground(Color.BLACK);
		titleBar.setPreferredSize(new Dimension(frame.getWidth(), 30)); // 明确设置高度
		titleBar.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));

		// 标题栏左侧图标
		JLabel iconLabel = new JLabel();
		try {
			ImageIcon icon = new ImageIcon(
					Toolkit.getDefaultToolkit().getImage(MainWin.class.getResource("/com/dongqb/exe/icon.png")));
			iconLabel.setIcon(new ImageIcon(icon.getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH)));
		} catch (Exception e) {
			// 加载失败时使用默认文本
			iconLabel.setText("LOGO");
			iconLabel.setForeground(Color.WHITE);
		}
		iconLabel.setOpaque(false);

		// 标题栏右侧关闭按钮
		JButton closeButton = new JButton("×");
		closeButton.setVerticalAlignment(SwingConstants.TOP);
		closeButton.setHorizontalAlignment(SwingConstants.RIGHT);
		closeButton.setFont(new Font("Arial", Font.BOLD, 16));
		closeButton.setForeground(Color.WHITE);
		closeButton.setContentAreaFilled(false);
		closeButton.setBorderPainted(false);
		closeButton.setFocusPainted(false);
		closeButton.addActionListener(e -> frame.setVisible(false));
		// 鼠标悬停效果
		closeButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				closeButton.setForeground(Color.RED);
			}

			@Override
			public void mouseExited(MouseEvent e) {
				closeButton.setForeground(Color.WHITE);
			}
		});

		// 添加拖拽功能
		titleBar.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				mouseX = e.getX();
				mouseY = e.getY();
			}
		});

		titleBar.addMouseMotionListener(new MouseAdapter() {
			@Override
			public void mouseDragged(MouseEvent e) {
				frame.setLocation(e.getXOnScreen() - mouseX, e.getYOnScreen() - mouseY);
			}
		});

		// 将组件添加到标题栏
		JPanel leftPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
		leftPanel.setOpaque(false);
		leftPanel.add(iconLabel);
		titleBar.add(leftPanel, BorderLayout.WEST);

		JLabel lblNewLabel = new JLabel("股票信息");
		lblNewLabel.setForeground(Color.LIGHT_GRAY);
		leftPanel.add(lblNewLabel);

		JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 5));
		rightPanel.setOpaque(false);
		rightPanel.add(closeButton);
		titleBar.add(rightPanel, BorderLayout.EAST);

		// 添加标题栏到主面板
		mainPanel.add(titleBar, BorderLayout.NORTH);

		JPanel contentPanel = new JPanel();
		mainPanel.add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);

		tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.setBounds(10, 73, 689, 387);
		contentPanel.add(tabbedPane);

		JPanel panel_1 = new JPanel();
		tabbedPane.addTab("分时", null, panel_1, null);
		panel_1.setLayout(null);

		panel_min = new JImagePanel();
		panel_min.setBounds(10, 10, 545, 338);
		panel_1.add(panel_min);

		sell_5 = new JLabel("卖5  1221.19  1593");
		sell_5.setBounds(565, 10, 116, 15);
		panel_1.add(sell_5);

		sell_4 = new JLabel("卖5  1221.19  1593");
		sell_4.setBounds(565, 35, 116, 15);
		panel_1.add(sell_4);

		sell_3 = new JLabel("卖5  1221.19  1593");
		sell_3.setBounds(565, 60, 116, 15);
		panel_1.add(sell_3);

		sell_2 = new JLabel("卖5  1221.19  1593");
		sell_2.setBounds(565, 85, 116, 15);
		panel_1.add(sell_2);

		sell_1 = new JLabel("卖5  1221.19  1593");
		sell_1.setBounds(565, 110, 116, 15);
		panel_1.add(sell_1);

		JLabel lblNewLabel_2 = new JLabel("--------------------");
		lblNewLabel_2.setHorizontalAlignment(SwingConstants.CENTER);
		lblNewLabel_2.setBounds(565, 167, 120, 15);
		panel_1.add(lblNewLabel_2);

		buy_1 = new JLabel("卖5  1221.19  1593");
		buy_1.setBounds(565, 222, 116, 15);
		panel_1.add(buy_1);

		buy_2 = new JLabel("卖5  1221.19  1593");
		buy_2.setBounds(565, 247, 116, 15);
		panel_1.add(buy_2);

		buy_3 = new JLabel("卖5  1221.19  1593");
		buy_3.setBounds(565, 272, 116, 15);
		panel_1.add(buy_3);

		buy_4 = new JLabel("卖5  1221.19  1593");
		buy_4.setBounds(565, 297, 116, 15);
		panel_1.add(buy_4);

		buy_5 = new JLabel("卖5  1221.19  1593");
		buy_5.setBounds(565, 322, 116, 15);
		panel_1.add(buy_5);

		npan = new JLabel("内盘");
		npan.setForeground(Color.GREEN);
		npan.setBounds(565, 149, 116, 15);
		panel_1.add(npan);

		wpan = new JLabel("外盘");
		wpan.setForeground(Color.RED);
		wpan.setBounds(565, 182, 116, 15);
		panel_1.add(wpan);

		panel_day = new JImagePanel();
		tabbedPane.addTab("日k", null, panel_day, null);

		panel_week = new JImagePanel();
		tabbedPane.addTab("周K", null, panel_week, null);

		panel_month = new JImagePanel();
		tabbedPane.addTab("月K", null, panel_month, null);
		// 添加切换监听器
		tabbedPane.addChangeListener(e -> {
			int index = tabbedPane.getSelectedIndex();
			// 根据 index 执行不同逻辑，例如：
			switch (index) {
			case 0:
				handleShowKline(0);
				break;
			case 1:
				handleShowKline(1);
				break;
			case 2:
				handleShowKline(2);
				break;
			case 3:
				handleShowKline(3);
				break;
			}
		});

		name = new JLabel("-");
		name.setForeground(Color.RED);
		name.setFont(new Font("宋体", Font.PLAIN, 16));
		name.setBounds(10, 5, 153, 27);
		contentPanel.add(name);

		prvice = new JLabel("-");
		prvice.setForeground(Color.RED);
		prvice.setFont(new Font("宋体", Font.PLAIN, 16));
		prvice.setBounds(10, 36, 153, 27);
		contentPanel.add(prvice);

		infoPane = new JTextPane();
		infoPane.setEnabled(false);
		infoPane.setEditable(false);
		infoPane.setContentType("text/html");
		infoPane.setBounds(173, 5, 526, 77);
		contentPanel.add(infoPane);
	}

	private void handleShowKline(int type) {
		if (panelRun != null) {
			panelRun.distory();
		}
		if (type == 0) {
			panelRun = this.panel_min;
			panelRun.setImageUrl("http://image.sinajs.cn/newchart/min/n/" + code + ".gif");
		} else if (type == 1) {
			panelRun = this.panel_day;
			panelRun.setImageUrl("http://image.sinajs.cn/newchart/daily/n/" + code + ".gif");
		} else if (type == 2) {
			panelRun = this.panel_week;
			panelRun.setImageUrl("http://image.sinajs.cn/newchart/weekly/n/" + code + ".gif");
		} else if (type == 3) {
			panelRun = this.panel_month;
			panelRun.setImageUrl("http://image.sinajs.cn/newchart/monthly/n/" + code + ".gif");
		}
		panelRun.startAutoRefresh();
	}

	/**
	 * 传入数据显示详情
	 * 
	 * @param d
	 */
	public void loadData(StockInfo info) {
		try {
			String[] d = info.getData();
			this.code = info.getBh();
			double zd = NumberUtil.parseDouble(d[32]);
			if (zd >= 0) {
				name.setForeground(Color.RED);
				prvice.setForeground(Color.RED);
			} else {
				name.setForeground(Color.GREEN);
				prvice.setForeground(Color.GREEN);
			}
			// 设置具体值
			name.setText(info.getMc() + " " + info.getBh());
			prvice.setText(info.getXj() + "  " + info.getZd());

			// ====== 构建 HTML 内容 ======
			StringBuilder html = new StringBuilder();
			html.append(
					"<html><body style='font-family:微软雅黑, Arial, sans-serif; font-size:9px; margin:0; padding:0px;'>");
			// 表格开始
			html.append("<table border='0' cellpadding='0' cellspacing='0' width='100%'>");
			// --- 第一行 ---
			html.append("<tr>");
			appendItem(html, "最高价", d[41]);
			appendItem(html, "最低价", d[42]);
			appendItem(html, "成交量", NumberUtil.div(d[36], "10000", 2) + "万");
			appendItem(html, "成交额", NumberUtil.div(d[37], "10000", 2) + "亿");
			html.append("</tr>");

			// --- 第二行 ---
			html.append("<tr>");
			appendItem(html, "换手率", d[38] + "%");
			appendItem(html, "振幅", d[43]);
			appendItem(html, "市盈率(动)", d[52]);
			appendItem(html, "市盈率(静)", d[53]);
			html.append("</div>");

			// --- 第三行 ---
			html.append("<tr>");
			appendItem(html, "流通市值", d[44]);
			appendItem(html, "总市值", d[45]);
			appendItem(html, "市净率", d[41] + "%");
			html.append("</tr>");
			html.append("</table></body></html>");
			infoPane.setText(html.toString());

			wpan.setText("外盘  " + d[7]);
			npan.setText("内盘  " + d[8]);

			buy_1.setText("买1  " + d[9] + "  " + d[10] + " ");
			buy_2.setText("买2  " + d[11] + "  " + d[12] + " ");
			buy_3.setText("买3  " + d[13] + "  " + d[14] + " ");
			buy_4.setText("买4  " + d[15] + "  " + d[16] + " ");
			buy_5.setText("买5  " + d[17] + "  " + d[18] + " ");

			sell_1.setText("卖1  " + d[19] + "  " + d[20] + " ");
			sell_2.setText("卖2  " + d[21] + "  " + d[22] + " ");
			sell_3.setText("卖3  " + d[23] + "  " + d[24] + " ");
			sell_4.setText("卖4  " + d[25] + "  " + d[26] + " ");
			sell_5.setText("卖5  " + d[27] + "  " + d[28] + " ");

			handleShowKline(tabbedPane.getSelectedIndex());
			// System.err.println(JSONUtil.toJsonStr(d));
		} catch (Exception e) {
			this.name.setText("解析失败");
			this.infoPane.setText("解析报错了!<br>报错原因:" + e.getMessage() + "<br>原内容" + JSONUtil.toJsonStr(info));
		}
	}

	// ====== 封装添加一个信息项的方法 ======
	private static void appendItem(StringBuilder html, String label, String value) {
		html.append("<td style='width:120px;'>").append("<span style='font-weight:bold; color:#333;'>").append(label)
				.append("：</span>").append("<span style='color:#555; margin-top:2px;'>").append(value).append("</span>")
				.append("</td>");
	}

	/**
	 * 显示，绑定显示位置
	 */
	public void show(Point point) {

		// 计算右下角坐标
		int x = point.x - frame.getWidth() - 2;
		int y = frame.getHeight() + 20;

		// 设置窗口位置
		frame.setLocation(x, y);
		frame.setVisible(true);
	}

	/**
	 * 隐藏窗口
	 */
	public void hide() {
		frame.setVisible(false);
		if (panelRun != null) {
			panelRun.distory();
		}
	}
}
